/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package org.netbeans.modules.j2ee.sun.ddloaders.multiview.web;

import java.util.ResourceBundle;
import javax.swing.JCheckBox;
import org.netbeans.modules.j2ee.sun.dd.api.ASDDVersion;
import org.netbeans.modules.j2ee.sun.dd.api.VersionNotSupportedException;
import org.netbeans.modules.j2ee.sun.dd.api.web.MyClassLoader;
import org.netbeans.modules.j2ee.sun.dd.api.web.SunWebApp;
import org.netbeans.modules.j2ee.sun.ddloaders.SunDescriptorDataObject;
import org.netbeans.modules.j2ee.sun.ddloaders.Utils;
import org.netbeans.modules.j2ee.sun.ddloaders.multiview.BaseSectionNodeInnerPanel;
import org.netbeans.modules.j2ee.sun.ddloaders.multiview.TextItemEditorModel;
import org.netbeans.modules.xml.multiview.ItemCheckBoxHelper;
import org.netbeans.modules.xml.multiview.ItemEditorHelper;
import org.netbeans.modules.xml.multiview.XmlMultiViewDataSynchronizer;
import org.netbeans.modules.xml.multiview.ui.SectionNodeView;
import org.openide.ErrorManager;
import org.openide.util.NbBundle;


/**
 *
 * @author Peter Williams
 */
public class SunWebClassLoaderPanel extends BaseSectionNodeInnerPanel {
	
    private final ResourceBundle webappBundle = NbBundle.getBundle(
            "org.netbeans.modules.j2ee.sun.ddloaders.multiview.web.Bundle");	// NOI18N
    
    private SunWebApp sunWebApp;

    public SunWebClassLoaderPanel(SectionNodeView sectionNodeView, final SunWebApp sunWebApp, 
            final ASDDVersion version) {
        super(sectionNodeView, version);
        this.sunWebApp = sunWebApp;

        initComponents();
        initUserComponents(sectionNodeView);
    }

    private void initUserComponents(SectionNodeView sectionNodeView) {
        showAS81Fields(as81FeaturesVisible);
        
        SunDescriptorDataObject dataObject = (SunDescriptorDataObject) sectionNodeView.getDataObject();
        XmlMultiViewDataSynchronizer synchronizer = dataObject.getModelSynchronizer();
        addRefreshable(new ClassLoaderCheckboxHelper(synchronizer, jChkClassLoader));
        addRefreshable(new ItemEditorHelper(jTxtExtraClassPath, new ExtraClasspathEditorModel(synchronizer)));
        if(as81FeaturesVisible) {
            addRefreshable(new ItemEditorHelper(jTxtDynamicReloadInterval, new DynamicReloadIntervalEditorModel(synchronizer)));
        }
        addRefreshable(new DelegateCheckboxHelper(synchronizer, jChkDelegate));
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        jChkClassLoader = new javax.swing.JCheckBox();
        jLblExtraClassPath = new javax.swing.JLabel();
        jTxtExtraClassPath = new javax.swing.JTextField();
        jLblDynamicReloadInterval = new javax.swing.JLabel();
        jTxtDynamicReloadInterval = new javax.swing.JTextField();
        jLblDelegate = new javax.swing.JLabel();
        jChkDelegate = new javax.swing.JCheckBox();

        setAlignmentX(LEFT_ALIGNMENT);
        setOpaque(false);
        setLayout(new java.awt.GridBagLayout());

        jChkClassLoader.setText(NbBundle.getMessage(SunWebClassLoaderPanel.class, "LBL_EnableClassLoader")); // NOI18N
        jChkClassLoader.setOpaque(false);
        jChkClassLoader.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jChkClassLoaderItemStateChanged(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(6, 6, 0, 5);
        add(jChkClassLoader, gridBagConstraints);
        jChkClassLoader.getAccessibleContext().setAccessibleName(webappBundle.getString("ACSN_ClassLoader")); // NOI18N
        jChkClassLoader.getAccessibleContext().setAccessibleDescription(webappBundle.getString("ACSD_ClassLoader")); // NOI18N

        jLblExtraClassPath.setLabelFor(jTxtExtraClassPath);
        jLblExtraClassPath.setText(NbBundle.getMessage(SunWebClassLoaderPanel.class, "LBL_ExtraClassPath_1")); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(6, 28, 0, 0);
        add(jLblExtraClassPath, gridBagConstraints);

        jTxtExtraClassPath.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTxtExtraClassPathKeyReleased(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(6, 6, 0, 5);
        add(jTxtExtraClassPath, gridBagConstraints);
        jTxtExtraClassPath.getAccessibleContext().setAccessibleName(webappBundle.getString("ACSN_ExtraClassPath")); // NOI18N
        jTxtExtraClassPath.getAccessibleContext().setAccessibleDescription(webappBundle.getString("ACSD_ExtraClassPath")); // NOI18N

        jLblDynamicReloadInterval.setLabelFor(jTxtDynamicReloadInterval);
        jLblDynamicReloadInterval.setText(NbBundle.getMessage(SunWebClassLoaderPanel.class, "LBL_DynamicReloadInterval_1")); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(6, 28, 0, 0);
        add(jLblDynamicReloadInterval, gridBagConstraints);

        jTxtDynamicReloadInterval.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTxtDynamicReloadIntervalKeyReleased(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(6, 6, 0, 5);
        add(jTxtDynamicReloadInterval, gridBagConstraints);
        jTxtDynamicReloadInterval.getAccessibleContext().setAccessibleName(webappBundle.getString("ACSN_DynamicReloadInterval")); // NOI18N
        jTxtDynamicReloadInterval.getAccessibleContext().setAccessibleDescription(webappBundle.getString("ACSD_DynamicReloadInterval")); // NOI18N

        jLblDelegate.setLabelFor(jChkDelegate);
        jLblDelegate.setText(NbBundle.getMessage(SunWebClassLoaderPanel.class, "LBL_ClassLoaderDelegate_1")); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(6, 28, 5, 0);
        add(jLblDelegate, gridBagConstraints);

        jChkDelegate.setOpaque(false);
        jChkDelegate.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jChkDelegateItemStateChanged(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(6, 6, 5, 5);
        add(jChkDelegate, gridBagConstraints);
        jChkDelegate.getAccessibleContext().setAccessibleName(webappBundle.getString("ACSN_ClassLoaderDelegate")); // NOI18N
        jChkDelegate.getAccessibleContext().setAccessibleDescription(webappBundle.getString("ACSD_ClassLoaderDelegate")); // NOI18N

        getAccessibleContext().setAccessibleName(webappBundle.getString("ACSN_ClassLoaderPanel")); // NOI18N
        getAccessibleContext().setAccessibleDescription(webappBundle.getString("ACSD_ClassLoaderPanel")); // NOI18N
    }// </editor-fold>//GEN-END:initComponents

    private void jTxtDynamicReloadIntervalKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTxtDynamicReloadIntervalKeyReleased
//        WebAppRoot bean = masterPanel.getBean();
//		if(bean != null) {
//			try {
//				bean.setDynamicReloadInterval(jTxtDynamicReloadInterval.getText());
//			} catch(java.beans.PropertyVetoException exception) {
//				jTxtDynamicReloadInterval.setText(bean.getDynamicReloadInterval());
//			}
//		}
    }//GEN-LAST:event_jTxtDynamicReloadIntervalKeyReleased

	private void jChkDelegateItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jChkDelegateItemStateChanged
//        WebAppRoot bean = masterPanel.getBean();
//		boolean state = Utils.interpretCheckboxState(evt);
//		if(bean != null) {
//			try {
//				bean.setDelegate(state);
//			} catch(java.beans.PropertyVetoException exception) {
//				jChkDelegate.setSelected(bean.isDelegate());
//			}
//		}
	}//GEN-LAST:event_jChkDelegateItemStateChanged

	private void jChkClassLoaderItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jChkClassLoaderItemStateChanged
//        WebAppRoot bean = masterPanel.getBean();
//		boolean state = Utils.interpretCheckboxState(evt);
//		if(bean != null) {
//			try {
//				bean.setClassLoader(state);
//			} catch(java.beans.PropertyVetoException exception) {
//				jChkClassLoader.setSelected(bean.isClassLoader());
//			}
//		}
//		enableClassLoaderFields(state);
	}//GEN-LAST:event_jChkClassLoaderItemStateChanged

	private void jTxtExtraClassPathKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTxtExtraClassPathKeyReleased
//        WebAppRoot bean = masterPanel.getBean();
//		if(bean != null) {
//			try {
//				bean.setExtraClassPath(jTxtExtraClassPath.getText());
//			} catch(java.beans.PropertyVetoException exception) {
//				jTxtExtraClassPath.setText(bean.getExtraClassPath());
//			}
//		}
	}//GEN-LAST:event_jTxtExtraClassPathKeyReleased
	
	
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JCheckBox jChkClassLoader;
    private javax.swing.JCheckBox jChkDelegate;
    private javax.swing.JLabel jLblDelegate;
    private javax.swing.JLabel jLblDynamicReloadInterval;
    private javax.swing.JLabel jLblExtraClassPath;
    private javax.swing.JTextField jTxtDynamicReloadInterval;
    private javax.swing.JTextField jTxtExtraClassPath;
    // End of variables declaration//GEN-END:variables
	
    private void enableClassLoaderFields(boolean enabled) {
        jLblExtraClassPath.setEnabled(enabled);
        jTxtExtraClassPath.setEnabled(enabled);
        jLblDynamicReloadInterval.setEnabled(enabled);
        jTxtDynamicReloadInterval.setEnabled(enabled);
        jLblDelegate.setEnabled(enabled);
        jChkDelegate.setEnabled(enabled);
    }
    
    // TODO after 5.0, generalize version based field display for multiple (> 2)
    // appserver versions.
    private void showAS81Fields(boolean visible) {
        jLblDynamicReloadInterval.setVisible(visible);
        jTxtDynamicReloadInterval.setVisible(visible);
    }
    
    private static MyClassLoader getMyClassLoader(SunWebApp sunWebApp, boolean create) throws VersionNotSupportedException{
        MyClassLoader cl = sunWebApp.getMyClassLoader();
        if(cl == null && create) {
            cl = sunWebApp.newMyClassLoader();
            sunWebApp.setMyClassLoader(cl);
        }
        return cl;
    }
    
    private class ExtraClasspathEditorModel extends TextItemEditorModel {

        public ExtraClasspathEditorModel(XmlMultiViewDataSynchronizer synchronizer) {
            super(synchronizer, true, true);
        }

        protected String getValue() {
            String result = null;
            try {
                if(as81FeaturesVisible) {
                    MyClassLoader cl = sunWebApp.getMyClassLoader();
                    result = (cl != null) ? cl.getExtraClassPath() : null;
                } else {
                    result = sunWebApp.getMyClassLoaderExtraClassPath();
                }
            } catch(VersionNotSupportedException ex) {
                ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
            }
            return result;
        }

        protected void setValue(String value) {
            try {
                if(as81FeaturesVisible) {
                    MyClassLoader cl = getMyClassLoader(sunWebApp, true);
                    cl.setExtraClassPath(value);
                } else {
                    sunWebApp.setMyClassLoaderExtraClassPath(value);
                }
            } catch(VersionNotSupportedException ex) {
                ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
            }
        }
    }
    
    private class DynamicReloadIntervalEditorModel extends TextItemEditorModel {

        public DynamicReloadIntervalEditorModel(XmlMultiViewDataSynchronizer synchronizer) {
            super(synchronizer, true, true);
        }

        protected String getValue() {
            try {
                MyClassLoader cl = sunWebApp.getMyClassLoader();
                return (cl != null) ? cl.getDynamicReloadInterval() : null;
            } catch(VersionNotSupportedException ex) {
                ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
            }
            return null;
        }

        protected void setValue(String value) {
            try {
                MyClassLoader cl = getMyClassLoader(sunWebApp, true);
                cl.setDynamicReloadInterval(value);
            } catch(VersionNotSupportedException ex) {
                ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
            }
        }
    }
    
    private class ClassLoaderCheckboxHelper extends ItemCheckBoxHelper {

        public ClassLoaderCheckboxHelper(XmlMultiViewDataSynchronizer synchronizer, JCheckBox component) {
            super(synchronizer, component);
        }
        
        public boolean getItemValue() {
            boolean state = false;
            
            try {
                if(as81FeaturesVisible) {
                    state = sunWebApp.getMyClassLoader() != null;
                } else {
                    state = sunWebApp.isMyClassLoader();
                }
            } catch(VersionNotSupportedException ex) {
                ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
            }
            
    		enableClassLoaderFields(state);        
            return state;
        }

        public void setItemValue(boolean value) {
            try {
                if(as81FeaturesVisible) {
                    if(value) {
                        getMyClassLoader(sunWebApp, true);
                    } else {
                        sunWebApp.setMyClassLoader(null);
                    }
                } else {
                    sunWebApp.setMyClassLoader(value);
                }
            } catch(VersionNotSupportedException ex) {
                ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
            }
            
    		enableClassLoaderFields(value);
        }
    }
    
    private class DelegateCheckboxHelper extends ItemCheckBoxHelper {

        public DelegateCheckboxHelper(XmlMultiViewDataSynchronizer synchronizer, JCheckBox component) {
            super(synchronizer, component);
        }

        public boolean getItemValue() {
            boolean result = false;
            try {
                if(as81FeaturesVisible) {
                    MyClassLoader cl = sunWebApp.getMyClassLoader();
                    result = (cl != null) ? Utils.booleanValueOf(cl.getDelegate()) : false;
                } else {
                    result = Utils.booleanValueOf(sunWebApp.getMyClassLoaderDelegate());
                }
            } catch(VersionNotSupportedException ex) {
                ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
            }
            return result;
        }

        public void setItemValue(boolean value) {
            try {
                if(as81FeaturesVisible) {
                    MyClassLoader cl = getMyClassLoader(sunWebApp, true);
                    cl.setDelegate(Boolean.toString(value));
                } else {
                    sunWebApp.setMyClassLoaderDelegate(Boolean.toString(value));
                }
            } catch(VersionNotSupportedException ex) {
                ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
            }
        }
    }
}
